from flask import Blueprint, request, jsonify, render_template
from . import teacher_api_bp, teacher_page_bp
from app.models import db, Student, Honor
from app.utils import token_required
import re

# 获取所有学生荣誉，支持类型筛选
@teacher_api_bp.route('/honor/all', methods=['GET'])
@token_required
def get_all_honors(current_user):
    honor_type = request.args.get('type', '')
    query = Honor.query
    if honor_type:
        query = query.filter_by(honor_type=honor_type)
    honors = query.all()
    result = []
    for h in honors:
        student = Student.query.get(h.student_id)
        result.append({
            'id': h.id,
            'title': h.title,
            'honor_type': h.honor_type,
            'level': h.level,
            'rank': h.rank,
            'organization': h.organization,
            'description': h.description,
            'date': h.date,
            'certificate_url': h.certificate_url,
            'student_name': student.name if student else '',
            'student_username': student.username if student else '',
        })
    return jsonify({'code': 200, 'honors': result})

# 获取所有已注册学生信息
@teacher_api_bp.route('/students', methods=['GET'])
@token_required
def get_students(current_user):
    students = Student.query.all()
    result = []
    for s in students:
        result.append({
            'username': s.username,
            'name': s.name,
            'gender': s.gender,
            'grade': s.grade,
            'class_name': s.class_name,
            'department': s.department,
            'phone': s.phone,
            'email': s.email,
            'created_at': s.created_at.strftime('%Y-%m-%d %H:%M:%S') if s.created_at else ''
        })
    return jsonify({'code': 200, 'students': result})

# 荣誉详情页面
@teacher_page_bp.route('/honor/<int:honor_id>')
def honor_detail_page(honor_id):
    honor = Honor.query.get_or_404(honor_id)
    student = Student.query.get(honor.student_id)
    is_img = bool(honor.certificate_url and re.search(r'\.(jpg|jpeg|png|gif|webp|svg)$', honor.certificate_url, re.I))
    honor_data = {
        'id': honor.id,
        'title': honor.title,
        'honor_type': honor.honor_type,
        'level': honor.level,
        'rank': honor.rank,
        'organization': honor.organization,
        'description': honor.description,
        'date': honor.date,
        'certificate_url': honor.certificate_url,
        'student_name': student.name if student else ''
    }
    return render_template('honor_detail.html', honor=honor_data, is_img=is_img) 